import { DeleteOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import { ProTable } from "@ant-design/pro-components";
import { Button, message } from "antd";
import { useRef, useState } from "react";
import PopconfirmButton from "@/components/PopconfirmButton";
import { delRole, getRoleList } from "@/services/role";
import AuthModle from "../user/AuthModle";
import AddModle from "./AddModle";
import AuthConfig from "./AuthConfig";
import { useAccess } from "@/hooks/access";

const App = () => {
  //获取状态字典数据
  // const [selectedRowKeys] = useState<React.Key[]>([]);
  const [updateKey, setUpdateKey] = useState<number>(0);
  const myTableRef = useRef<any>(null);
  const [pageNum, setPageNum] = useState<number>(1);
  const [pageSize, setPageSize] = useState<number>(10);
  const [addOpen, setAddOpen] = useState<boolean>(false);
  const [roleId, setRoleId] = useState<string | undefined>(undefined);
  const [ruleAuthOpen, setRuleAuthOpen] = useState<boolean>(false);
  const formRef = useRef<any>(null);
  const [authOpen, setAuthOpen] = useState<boolean>(false);
  const { permissions } = useAccess();

  const canAddUser = permissions.includes("system:role:add");
  const canEditUser = permissions.includes("system:role:edit");
  const canRemoveUser = permissions.includes("system:role:remove");
  const canExportUser = permissions.includes("system:role:export");
  const canQueryUser = permissions.includes("system:role:query");
  const canListUser = permissions.includes("system:role:list");

  // 表格列配置
  const columns = [
    //权限字符
    {
      title: "角色代码",
      dataIndex: "roleKey",
      key: "roleKey",
      width: 150,
    },
    //角色编号
    // {
    //   title: '角色编号',
    //   dataIndex: 'roleId',
    //   key: 'roleId',
    //   search: false,
    // },
    {
      title: "角色名称",
      dataIndex: "roleName",
      key: "roleName",
      width: 150,
    },

    {
      title: "简介",
      dataIndex: "remark",
      key: "remark",
      search: false,
    },
    //状态
    // {
    //   title: "状态",
    //   dataIndex: "status",
    //   key: "status",
    //   valueType: "select",
    //   valueEnum: statusOptions.reduce((prev, curr) => {
    //     prev[curr.value] = { text: curr.label };
    //     return prev;
    //   }, {} as Record<string, { text: string }>),
    //   // render <Switch /> 组件
    //   render: (_: any, record: any) => {
    //     return (
    //       <Switch
    //         disabled={record.admin}
    //         defaultChecked={record.status === "0"}
    //         checkedChildren="正常"
    //         unCheckedChildren="停用"
    //         onChange={async (checked) => {
    //           const { success, msg } = await changeRoleStatus({
    //             roleId: record.roleId,
    //             status: checked ? "0" : "1",
    //           });
    //           if (success) {
    //             message.success("状态修改成功");
    //           } else {
    //             message.error(msg || "状态修改失败");
    //           }
    //           // setUpdateKey(Date.now());
    //         }}
    //       />
    //     );
    //   },
    // },
    //创建时间
    {
      title: "人员配置",
      dataIndex: "config",
      key: "config",
      search: false,
      width: 150,
      render: (_: any, record: any) => {
        if (!canEditUser) {
          return <>--</>;
        }
        return (
          <Button
            size="small"
            type="link"
            onClick={() => {
              setRoleId(record.roleId);
              setRuleAuthOpen(true);
            }}
          >
            人员配置
          </Button>
        );
      },
    },
    //操作
    {
      title: "操作",
      dataIndex: "option",
      valueType: "option",
      width: 200,
      render: (_: any, record: any) =>
        record.admin
          ? []
          : [
              canEditUser ? (
                <Button
                  disabled={record.admin}
                  onClick={() => {
                    setRoleId(record.roleId);
                    setAddOpen(true);
                  }}
                  icon={<EditOutlined />}
                  type="link"
                  size="small"
                  key="edit"
                >
                  编辑
                </Button>
              ) : null,
              // <Button icon={<DeleteOutlined />} type="link" size="small" key="delete">
              //   删除
              // </Button>,
              canRemoveUser ? (
                <PopconfirmButton
                  size="small"
                  type="link"
                  title={`确定删除 " ${record.roleName} " 吗？`}
                  onConfirm={() => {
                    delItem(record.roleId);
                  }}
                  disabled={record.admin}
                  icon={<DeleteOutlined />}
                  key="delete"
                  danger={false}
                >
                  删除
                </PopconfirmButton>
              ) : null,

              // <TableDropdown
              //   key="actionGroup"
              //   // onSelect={() => action?.reload()}
              //   menus={[
              //     {
              //       key: "copy",
              //       disabled: record.admin,
              //       name: "数据权限",
              //       onClick: () => {
              //         setRoleId(record.roleId);
              //         setAuthOpen(true);
              //       },
              //     },
              //     {
              //       key: "delete",
              //       disabled: record.admin,
              //       onClick: () => {
              //         history.push(`/system/user/auth/${record.roleId}`);
              //       },
              //       name: "分配用户",
              //     },
              //   ]}
              // />,
            ],
    },
  ];
  // const rowSelection: TableProps<DataType>["rowSelection"] = {
  //   onChange: (selectedRowKeys: React.Key[]) => {
  //     setSelectedRowKeys(selectedRowKeys);
  //   },
  //   getCheckboxProps: (record: any) => ({
  //     disabled: record.admin, // Column configuration not to be checked
  //   }),
  // };
  const delItem = async (ids: string) => {
    const { code } = await delRole(ids);
    if (code === 200) {
      message.success("删除成功");
      myTableRef.current?.reload();
    } else {
      // message.error(msg || '删除失败');
    }
  };

  return (
    <>
      <ProTable
        scroll={{
          x: 1000,
        }}
        key={updateKey}
        //如果没有编辑权限，就不显示操作栏
        columns={
          canEditUser || canRemoveUser
            ? columns
            : columns.filter((column) => column.dataIndex !== "option")
        }
        actionRef={myTableRef}
        search={{
          defaultCollapsed: false,
        }}
        // rowSelection={rowSelection}
        rowKey="roleId"
        request={async (params) => {
          console.clear();
          // console.log(params); //表单查询参数
          const { code, total, rows } = await getRoleList({
            pageNum,
            pageSize,
            ...params,
          });
          // 返回这种种
          return {
            data: rows,
            total,
            success: code === 200,
          };
        }}
        toolBarRender={() => [
          canAddUser ? (
            <Button
              ghost
              size="small"
              onClick={() => {
                setRoleId(undefined);
                setAddOpen(true);
              }}
              icon={<PlusOutlined />}
              key="button"
              type="primary"
            >
              新增
            </Button>
          ) : null,
          // <Button
          //   disabled={selectedRowKeys.length !== 1}
          //   onClick={() => {
          //     setRoleId(selectedRowKeys[0] as string);
          //     setAddOpen(true);
          //   }}
          //   icon={<EditOutlined />}
          //   key="button"
          // >
          //   编辑
          // </Button>,
          // <PopconfirmButton
          //   title={`确定删${selectedRowKeys?.join(",")}除吗？`}
          //   onConfirm={() => {
          //     delItem(selectedRowKeys?.join(","));
          //   }}
          //   disabled={selectedRowKeys.length === 0}
          //   icon={<DeleteOutlined />}
          //   key="button"
          //   danger
          // >
          //   删除
          // </PopconfirmButton>,
        ]}
        //分布功能
        pagination={{
          current: pageNum,
          pageSize,
          showSizeChanger: true,
          onChange: (page, size) => {
            setPageNum(page);
            setPageSize(size || 10);
          },
        }}
      />
      {addOpen ? (
        <AddModle
          ref={formRef}
          roleId={roleId}
          onClose={(reflash) => {
            setAddOpen(false);
            setRoleId(undefined);
            if (reflash) {
              setUpdateKey(Date.now());
              myTableRef.current?.reload();
            }
          }}
        />
      ) : null}

      {authOpen ? (
        <AuthConfig
          roleId={roleId as any}
          onClose={(reflash) => {
            setAuthOpen(false);
            if (reflash) {
              myTableRef.current?.reload();
            }
          }}
        />
      ) : null}

      {ruleAuthOpen ? (
        <AuthModle
          roleId={roleId}
          onOk={() => {
            setRoleId(undefined);
            setRuleAuthOpen(false);
            myTableRef.current?.reload();
          }}
          onClose={(reflash) => {
            setRuleAuthOpen(false);
            setRoleId(undefined);
            if (reflash) {
              myTableRef.current?.reload();
            }
          }}
        />
      ) : null}
    </>
  );
};
export default App;
